/**
 * Copyright @2016-present, Sumscope, Inc.
 * All rights reserved.
 */

const winston = require('winston');
const dailyRotate = require('winston-daily-rotate-file');
const moment = require('moment');
const path = require('path');
const fs = require('fs');
const config = require('../config');

function buildOptions() {
  let options = config.log;
  options.transports = [];
  if (options.output.includes('console')) {
    options.transports.push(buildConsole());
  }
  if (options.output.includes('file')) {
    options.transports.push(buildFile(options));
  }
  return options;
}

function buildConsole() {
  return new (winston.transports.Console)({
    colorize: true,
    timestamp: function () {
      return moment().format('YYYY-MM-DD hh:mm:ss');
    }
  });
}

function buildFile(config) {
  let logPath = config.path;
  if (!fs.existsSync(logPath)) {
    fs.mkdirSync(logPath);
  }
  const instanceTag = process.env.NODE_APP_INSTANCE ? '-' + process.env.NODE_APP_INSTANCE : '';
  return new dailyRotate({
    json: false,
    colorize: true,
    timestamp: function () {
      return moment().format('YYYY-MM-DD hh:mm:ss');
    },
    maxsize: '10000000',
    maxFiles: 100,
    // handleExceptions: true,
    filename: path.join(logPath, config.filename),
    datePattern: '-yyyy-MM-dd.log'
  });
}

module.exports = exports = new winston.Logger(buildOptions());
